package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ProductType(ProductChannelConstant.GUAZI)
public class GuaZiReport extends AbstractProductReport{
    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {
        Map<String, Object> prams = new HashMap<>();
        prams.put("ip", reportDTO.getIp());
        prams.put("ts", reportDTO.getTraceTime());
        prams.put("media_type", "androidDefault");
        if (StringUtils.isNotBlank(reportDTO.getUser_agent())) {
            String ua = URLEncoderDecoderTool.decodeURL(reportDTO.getUser_agent());
            prams.put("ua", URLEncoderDecoderTool.encodeURL(ua));
        }

        if(StringUtils.isNotBlank(reportDTO.getImei()) &&!StringUtils.contains(reportDTO.getImei(),"__")){
            prams.put("imei", reportDTO.getImei());
        }
        if(StringUtils.isNotBlank(reportDTO.getImeiSum()) &&!StringUtils.contains(reportDTO.getImeiSum(),"__")){
            prams.put("md5Imei", reportDTO.getImeiSum());
        }
        if(StringUtils.isNotBlank(reportDTO.getOaid()) &&!StringUtils.contains(reportDTO.getOaid(),"__")){
            prams.put("oaid", reportDTO.getOaid());
        }
        if(StringUtils.isNotBlank(reportDTO.getOaidSum()) &&!StringUtils.contains(reportDTO.getOaidSum(),"__")){
            prams.put("md5Oaid", reportDTO.getOaidSum());
        }
        if(StringUtils.isNotBlank(reportDTO.getHash_android_id()) &&!StringUtils.contains(reportDTO.getHash_android_id(),"__")){
            prams.put("md5AndroidId", reportDTO.getHash_android_id());
        }

        String callBackUrl = String.format(productConfigDTO.getCallbackUrl(), reportDTO.getBizRequestId());
        String paramsUrl = URLUtil.buildQuery(prams, StandardCharsets.UTF_8);

        String finalUrl = ocpxAccountDTO.getReportUrl() + "&" + paramsUrl+"&callback="+URLEncoderDecoderTool.encodeURL(callBackUrl);

        log.info("账号为{},请求产品端的完整地址为 {}",ocpxAccountDTO.getId(),finalUrl);
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 请求产品端，响应的结果为{}",ocpxAccountDTO.getId(),  body);


        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }
}
